#include "LightScene.h"

LightScene::LightScene(LPDIRECT3DDEVICE9 _d3ddev)
{	
	LoadContent(_d3ddev);

	_d3ddev->CreateVertexBuffer(24*sizeof(CUSTOMVERTEX),0,CUSTOMFVF,D3DPOOL_MANAGED,&v_buffer,NULL);
	_d3ddev->CreateIndexBuffer(36*sizeof(short),0,D3DFMT_INDEX16,D3DPOOL_MANAGED,&i_buffer,NULL);
	void * pVoid;
	v_buffer->Lock(0,0,(void**)&pVoid,0);	//lockear el buffer
	memcpy(pVoid,OurVertices,sizeof(OurVertices));	//copiar vertices
	v_buffer->Unlock();
	i_buffer->Lock(0,0,(void**)&pVoid,0);
	memcpy(pVoid,indices,sizeof(indices));
	i_buffer->Unlock();
}

void LightScene::LoadContent(LPDIRECT3DDEVICE9 _d3ddev)
{	
	lightRotation = 0;
	//Load Meshes////////////////////////////////////////////////////////////////////////////////////////////////////
	//Load Tank
	HRESULT hr = D3DXLoadMeshFromX("sphere.x",D3DXMESH_SYSTEMMEM,_d3ddev,NULL,&materialBuffer,NULL,&numMaterials,&mesh);
	//HRESULT hr = D3DXLoadMeshFromX("plane.x",D3DXMESH_SYSTEMMEM,_d3ddev,NULL,&materialBuffer,NULL,&numMaterials,&mesh);
	d3dxPlaneMaterials = (D3DXMATERIAL *) materialBuffer->GetBufferPointer();

	meshPlaneMaterials = new D3DMATERIAL9[numMaterials];
	meshPlaneTextures = new LPDIRECT3DTEXTURE9[numMaterials];
	
	for(DWORD i=0;i<numMaterials;i++)
	{
		//Copiar Material
		meshPlaneMaterials[i] = d3dxPlaneMaterials[i].MatD3D;
		//Setea el color ambiente
		meshPlaneMaterials[i].Ambient = meshPlaneMaterials[i].Diffuse;
		//crea la textura si existe
		meshPlaneTextures[i] = NULL;

		if(d3dxPlaneMaterials[i].pTextureFilename)
			D3DXCreateTextureFromFile(_d3ddev,d3dxPlaneMaterials[i].pTextureFilename,&meshPlaneTextures[i]);
	}
	materialBuffer->Release();
	MeshInfo * meshInfoTank = new MeshInfo();
	meshInfoTank->mesh = mesh;
	meshInfoTank->meshMaterials = meshPlaneMaterials;
	meshInfoTank->meshTextures = meshPlaneTextures;
	meshInfoTank->numMaterials = numMaterials;

	light.setMesh(meshInfoTank);
	//cameraPlane.setPosition(D3DXVECTOR3(0,-768/2.25f,0));
	light.setPosition(D3DXVECTOR3(0,15,0));
	//cameraPlane.setScale(D3DXVECTOR3(2.5f,5,1));
	light.setScale(D3DXVECTOR3(0.06f,0.06f,0.06f));
	//cameraPlane.setAngle(D3DXVECTOR3(-45,0,0));

	light.calculateBoundingBox();
}
LightScene::~LightScene()
{

}
void LightScene::Draw(LPDIRECT3DDEVICE9 _d3ddev)
{
	float* lp = new float[3];
	lp[0] = light.getPosition().x;
	lp[1] = light.getPosition().y;
	lp[2] = light.getPosition().z;
	cgSetParameter3fv(lightPos,lp);

	light.Draw(_d3ddev,true);
	//light.Draw(_d3ddev,v_buffer,i_buffer);
}
void LightScene::Update(DWORD dt)
{	
	lightRotation +=0.05f;
	light.setPosition(D3DXVECTOR3(cos(lightRotation)*25,10+cos(lightRotation)*15,sin(lightRotation)*40));
	light.Update(dt);
}
void LightScene::HandleInput(InputManager * _input)
{
	
}
void LightScene::Init()
{

}